package com.hongkuncheng.cms.controller.admin;

import java.util.List;

import org.hibernate.LockMode;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.model.Datamodel;
import com.hongkuncheng.cms.model.DatamodelType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 数据模型管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/datamodel")
public class AdatamodelController extends BaseController {

    // 数据模型列表
    @RequestMapping
    public String index() {
        List<Datamodel> datamodels = factorySession.createCriteria(Datamodel.class).list();
        request.setAttribute("datamodels", datamodels);
        return view();
    }

    // 数据模型编辑
    @RequestMapping("edit")
    public String edit() {
        int datamodelId = request.getParameter("datamodelid") == null ? 0 :
                Integer.parseInt(request.getParameter("datamodelid"));
        Datamodel datamodel = datamodelId == 0 ? new Datamodel() : factorySession.get(Datamodel.class, datamodelId);
        request.setAttribute("datamodel", datamodel);
        List<DatamodelType> datamodelTypes = factorySession.createCriteria(DatamodelType.class).list();
        request.setAttribute("datamodelTypes", datamodelTypes);
        return view();
    }

    // 数据模型编辑处理
    @RequestMapping("editdo")
    @ResponseBody
    public void editdo() {
        checkAdminPermission("yunwei_webmaintain_datamodel");
        int datamodelId = Integer.parseInt(request.getParameter("datamodelid"));
        Datamodel datamodel = datamodelId == 0 ? new Datamodel() :
                factorySession.load(Datamodel.class, datamodelId, LockMode.PESSIMISTIC_WRITE);
        datamodel.setName(request.getParameter("name"));
        int datamodelTypeId = Integer.parseInt(request.getParameter("datamodetypeid"));
        datamodel.setDatamodelType(factorySession.load(DatamodelType.class, datamodelTypeId));
        if (datamodelId == 0) factorySession.save(datamodel);
        recordLog((datamodelId == 0 ? "新建" : "更新") + "数据模型《" + datamodel.getName().trim() + "》");
        PageHelper.alertAndRedirect("保存成功", "./");
    }

    // 数据模型删除
    @RequestMapping("delete")
    @ResponseBody
    public void delete() {
        checkAdminPermission("yunwei_webmaintain_datamodel");
        int datamodelId = Integer.parseInt(request.getParameter("datamodelid"));
        Datamodel datamodel = factorySession.load(Datamodel.class, datamodelId, LockMode.PESSIMISTIC_WRITE);
        factorySession.delete(datamodel);
        recordLog("删除数据模型《" + datamodel.getName().trim() + "》");
        PageHelper.alertAndRedirect("删除成功", "./");
    }

}
